//
//  SNKTabBarView.m
//  SleepNews
//
//  Created by Kavee DJ on 2016/12/8.
//  Copyright © 2016年 Kavee DJ. All rights reserved.
//

#import "SNKTabBarView.h"
#import "SNKTabBarButton.h"

#import <DKNightVersion.h>

@interface SNKTabBarView ()

/** 记录选中的Button */
@property (nonatomic, weak) SNKTabBarButton *selectedButton;
/** 记录添加的Button */
@property (nonatomic, weak) SNKTabBarButton *tempTabBarButton;

@end

@implementation SNKTabBarView

- (instancetype)init {
    if (self = [super init]) {
        // 颜色相关
        self.dk_backgroundColorPicker = DKColorPickerWithKey(BAR);
    };
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    // 自定义按钮的大小
    CGFloat buttonW = self.kdj_width / self.subviews.count;
    CGFloat buttonY = 0;
    CGFloat buttonH = self.kdj_height;
    
    for (NSInteger index = 0; index < self.subviews.count; index++) {
        // 取出系统原来tabBar上面的按钮
        SNKTabBarButton *button = self.subviews[index];
        CGFloat buttonX = index * buttonW;
        button.frame = CGRectMake(buttonX, buttonY, buttonW, buttonH);
        
        // 设置按钮的tag值
        button.tag = index;
    }
}

- (void)selectIndex:(int)index {
    SNKTabBarButton *btn = self.subviews[index];
    btn.tag = index;
    [self buttonClick:btn];
}

- (void)addTabBarButtonWithItem:(UITabBarItem *)item {
    // 创建按钮
    SNKTabBarButton *button = [[SNKTabBarButton alloc] init];
    [self addSubview:button];
    self.tempTabBarButton = button;
    
    // 设置
    button.item = item;
    
    // 监听按钮点击
    [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchDown];
    
    // 默认选中第一个按钮
    if (self.subviews.count == 1) {
        [self buttonClick:button];
    }
}

- (void)buttonClick:(SNKTabBarButton *)btn {
    if (self.btnSelectBlock) {
        self.btnSelectBlock((NSInteger)btn.tag);
    }
    
    if (btn.tag == self.selectedButton.tag) {
        [[NSNotificationCenter defaultCenter] postNotificationName:btn.titleLabel.text object:nil];
    }
    
    self.selectedButton.selected = NO;
    btn.selected = YES;
    self.selectedButton = btn;
}

@end
